package studio.raptor.ddal.dashboard.api;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import studio.raptor.ddal.dashboard.ddl.DdlExecuteUtil;
import studio.raptor.ddal.jdbc.RaptorDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Properties;

/**
 * @author liujy
 * @since 3.0.0
 */
@RestController
public class DdlController {

  private static DataSource dataSource;
  private static Connection connection;
  private static DdlExecuteUtil ddlExecuteUtil;

  static{
    try{
      if(null == dataSource) {
        Properties systemProperties = new Properties();
        try {
          systemProperties.load( DdlController.class.getResourceAsStream("/system.properties"));
          String virtualDb=systemProperties.getProperty( "virtualdb.name" );
          String databaseDialect=systemProperties.getProperty( "physicaldbcluster.type" );
          dataSource = new RaptorDataSource(virtualDb, databaseDialect);
        } catch (Exception ioe) {
          ioe.printStackTrace();
        }
      }
      if(null == connection){
        connection = dataSource.getConnection();
      }
      if(null == ddlExecuteUtil){
        ddlExecuteUtil=new DdlExecuteUtil();
        ddlExecuteUtil.init( dataSource,connection );
      }
    }catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  @RequestMapping("/ddl/test")
  public String index() {
    System.out.println( "DdlController.index dataSource" +dataSource.toString());
    System.out.println( "DdlController.index connection" +connection.toString() );
    return "Greetings from Spring Boot!";
  }

  @RequestMapping(value = "/ddl/execute")
  public String ddlExecute(@RequestBody String sql){
    try{
      return ddlExecuteUtil.executeDdl( sql );
    }catch (Exception e){
      return "操作失败："+e.getMessage();
    }
  }

  @RequestMapping(value = "/dml/executeIUD")
  public String executeIUD(@RequestBody String sql){
    try{
      return ddlExecuteUtil.executeIUD( sql );
    }catch (Exception e){
      return "操作失败："+e.getMessage();
    }
  }

  @RequestMapping(value = "/dml/executeSelect")
  public String executeSelect(@RequestBody String sql){
    try{
      String respMsg= ddlExecuteUtil.executeSelect( sql );
      return  respMsg;
    }catch (Exception e){
      String respMsg=e.getMessage();
      respMsg=respMsg.replace("\n","");
      respMsg=respMsg.replace("\"","'");
      respMsg="{\"respMsg\":\"操作失败："+respMsg+"\"}";
      return respMsg;
    }
  }

}
